package com.cfxy.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.cfxy.dao.daoImply.MessagerDaoImpl;
import com.cfxy.model.Message;

/**
 * Servlet implementation class MessageManager
 */
@WebServlet("/messagemanager")
public class MessageManager extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String func = request.getParameter("funcation");
		if("add".equals(func))add(request,response);
		else if("show".equals(func))show(request,response);
		else if("delete".equals(func))delete(request,response);
		else if("logout".equals(func))logout(request,response);
		else if("update".equals(func))add(request,response);
		else add(request,response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		Message m = new Message();
		m.setTitle(title);
		m.setContent(content);
		new MessagerDaoImpl().insert(m);
		show(request,response);	
		}
	public void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		List<Message> list = new MessagerDaoImpl().getall();
		request.setAttribute("messagelist",list);
		request.getRequestDispatcher("Message/showall.jsp").forward(request, response);
		}
	public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String id = request.getParameter("id");
		new MessagerDaoImpl().delete(Integer.parseInt(id));
		show(request,response);
		}
	public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.getSession().removeAttribute("uuser");
		response.sendRedirect("/guestbook1/login.jsp");
		}
}

